<template>
  <slot
    ><el-button icon="Upload" @click="handleOpenDialog">导入</el-button></slot
  >
  <basic-dialog :title="title" :width="width" v-model="visible">
    <ul>
      <li>
        第一步、<el-button
          link
          type="primary"
          @click="handleDownTemp"
          :loading="downLoading"
          >下载模板</el-button
        >
      </li>
      <li>
        第二步、文件上传：<el-upload
          ref="upload"
          :limit="1"
          :before-upload="handleUpBefore"
          :on-remove="handleRemove"
          :http-request="handleUpload"
          :loading="uploadLoading"
          :accept="accept"
        >
          <el-button type="primary" icon="el-icon-upload">点击上传</el-button>
        </el-upload>
      </li>
    </ul>
    <template #footer>
      <el-button @click="visible = false" type="primary">关闭</el-button>
    </template>
  </basic-dialog>
</template>

<script setup>
import { apiDownTemplate, apiUploadFile } from '@/apis/global'

const props = defineProps({
  title: {
    type: String,
    default: '导入',
  },
  width: {
    type: String,
    default: '600',
  },
  // 模板下载地址
  templateUrl: {
    type: String,
    default: '',
  },
  // 文件上传地址
  uploadUrl: {
    type: String,
    default: '',
  },
  // 文件最大大小
  maxSize: {
    type: Number,
    default: 10,
  },
  accept: {
    type: String,
    default: '',
  },
})

const emits = defineEmits(['AfterUploadSuccess'])
const visible = ref(false)
const handleOpenDialog = () => {
  visible.value = true
}
// 下载模板
const downLoading = ref(false)
const handleDownTemp = async () => {
  if (!props.templateUrl) {
    return ElMessage.error('模板地址错误！')
  }
  apiDownTemplate(props.templateUrl, downLoading)
}
const uploadLoading = ref(false)
const handleUpBefore = (file) => {
  let isRightSize = file.size / 1024 / 1024 < 10
  if (!isRightSize) {
    ElMessage.error('文件带下超出限制，最大为' + props.maxSize + 'M')
  }
  return isRightSize
}
// 文件上传
const handleUpload = async (params) => {
  let formData = new FormData()
  formData.append('file', params.file)
  await apiUploadFile(props.uploadUrl, formData, uploadLoading)
  ElMessage.success('导入成功')
  emits('AfterUploadSuccess')
  visible.value = false
}
</script>

<style lang="scss" scoped>
ul {
  padding: 0 20px;
  margin: 0;
  li {
    display: flex;
    margin: 10px 0;
    align-items: center;
  }
}
</style>
